package com.xpsoft.oa.workflow.event;

import java.math.BigDecimal;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.produce.MaterialOutStock;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.produce.MaterialOutStockService;
import com.xpsoft.oa.service.produce.MaterialService;
import com.xpsoft.oa.service.project.ProjectService;

public class MaterialOutStockFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(MaterialOutStockFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String proId = (String)pi.getVariable("materialOutStock.project.id");
		Date inStockDate = (Date)pi.getVariable("materialOutStock.outStockDate");
		String inStockNo = (String)pi.getVariable("materialOutStock.outStockNo");
		String materialId = (String)pi.getVariable("materialOutStock.material.id");
		Integer num = (Integer)pi.getVariable("materialOutStock.num");
		BigDecimal unitPrice = (BigDecimal)pi.getVariable("materialOutStock.unitPrice");
		String remark = (String)pi.getVariable("materialOutStock.remark");
		
		MaterialOutStock materialOutStock = new MaterialOutStock();
		materialOutStock.setOutStockDate(inStockDate);
		materialOutStock.setOutStockNo(inStockNo);
		materialOutStock.setNum(num);
		materialOutStock.setUnitPrice(unitPrice);
		materialOutStock.setRemark(remark);
		
		if(StringUtils.isNotBlank(proId)){
			ProjectService projectService = (ProjectService)AppUtil.getBean("projectService");
			materialOutStock.setProject(projectService.get(Long.valueOf(proId)));
		}
		if(StringUtils.isNotBlank(materialId)){
			MaterialService materialService = (MaterialService)AppUtil.getBean("materialService");
			materialOutStock.setMaterial(materialService.get(Long.valueOf(materialId)));
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		materialOutStock.setProcessRunId(processRun.getRunId());
		
		MaterialOutStockService materialOutStockService = (MaterialOutStockService)AppUtil.getBean("materialOutStockService");
		materialOutStockService.save(materialOutStock);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
